<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use App\Models\AnswerRecord;
use Log, DB;
use Mockery\CountValidator\Exception;

class HomeController extends Controller
{


    /*登录页*/
    public function index()
    {
        //Log::info('return response.');
        return view('index');
    }

    /*答题页*/
    public function exam()
    {
        return view('exam');
    }

    /*得分页*/
    public function score(Request $request)
    {
        /*$id = $request->get('id');
        if($id){
            $record= DB::table('answer_record')->where(['id'=>$id])->get()[0];
            $score=$record->user_score;
        }else{
            $score=0;
        }

        if(empty($record)){
            return view('index');
        }else{
            return view('score', compact(['score']));
        }*/

        return view('score');
    }

    /*计算分数*/
    public function make_score(Request $request)
    {
        //data:{'user':user,'exam_form':exam_form,'minute':minute,'second':second},

        $user = json_decode($request->get('user'));
        $form_data = json_decode($request->get('exam_form'));
        $answer = config('answer.value');

        //todo 验证输入信息规则
        $score=0;

        if(!empty($form_data)){
            foreach ($form_data as $key=>$value)
            {
                if(gettype($value)==="array"){
                    $value=implode(',',$value);
                }
                if($answer[$key]==$value){
                    $score+=5;
                }
            }
        }
        if(empty($user)||empty($user->username)||empty($user->phone)||empty($user->city)||empty($user->school)){
            return response()->json(["code" => 0, "message" => '请填写用户信息']);
        }


/*        dd([
            'user_name' => $user?$user->username:'',
            'user_phone' => $user?$user->phone:'',
            'user_city' => $user?$user->city:'',
            'user_school' => $user?$user->school:'',
            'user_score' => $score,
            'created_at'=>time(),
            'updated_at'=>time(),
        ]);*/
        
        try {
            $date = date("Y-m-d H:i:s",time());
            $id = DB::table('answer_record')->insert([
                'user_name' => $user?$user->username:'',
                'user_phone' => $user?$user->phone:'',
                'user_city' => $user?$user->city:'',
                'user_school' => $user?$user->school:'',
                'user_score' => $score,
                'created_at'=>$date,
                'updated_at'=>$date,
            ]);
            return response()->json(["code" => 1, "message" => '提交成功', "id" => $score]);

        } catch (Exception $e) {
            return response()->json(["code" => 0, "message" => '数据库链接错误']);
        }

    }
}